<template>
  <el-card>
    <el-button type="primary" @click="openAddDialog">新增课程</el-button>
    <el-table :data="courseList" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="courseId" label="课程ID" width="80" />
      <el-table-column prop="userId" label="用户ID" />
      <el-table-column prop="courseName" label="课程名称" />
      <el-table-column prop="courseTime" label="课程时间" />
      <el-table-column prop="location" label="地点" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDeleteCourse(scope.row.courseId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form">
        <el-form-item label="用户ID">
          <el-input v-model="form.userId" />
        </el-form-item>
        <el-form-item label="课程名称">
          <el-input v-model="form.courseName" />
        </el-form-item>
        <el-form-item label="课程时间">
          <el-input v-model="form.courseTime" />
        </el-form-item>
        <el-form-item label="地点">
          <el-input v-model="form.location" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getCoursesByUserId, addCourse, updateCourse, deleteCourse } from '@/api/course';
import { ElMessageBox } from 'element-plus';

const courseList = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('新增课程');
const form = ref({ courseId: null, userId: '', courseName: '', courseTime: '', location: '' });
let isEdit = false;

const loadCourses = async () => {
  courseList.value = await getCoursesByUserId(1); // 替换成当前用户ID
};

const openAddDialog = () => {
  isEdit = false;
  dialogTitle.value = '新增课程';
  form.value = { courseId: null, userId: '', courseName: '', courseTime: '', location: '' };
  dialogVisible.value = true;
};

const openEditDialog = (course) => {
  isEdit = true;
  dialogTitle.value = '编辑课程';
  form.value = { ...course };
  dialogVisible.value = true;
};

const submitForm = async () => {
  if (isEdit) {
    await updateCourse(form.value);
  } else {
    await addCourse(form.value);
  }
  dialogVisible.value = false;
  loadCourses();
};

// ⚙️ 重命名后的删除函数，防止命名冲突
const handleDeleteCourse = async (courseId) => {
  await ElMessageBox.confirm('确定删除该课程吗?', '提示', { type: 'warning' });
  await deleteCourseById(courseId);
};

const deleteCourseById = async (courseId) => {
  await deleteCourse(courseId);
  loadCourses();
};

onMounted(() => {
  loadCourses();
});
</script>
